package com.taotao.delayjob.core.config;


import com.github.pagehelper.PageInterceptor;
import com.taotao.delayjob.core.RetryTaskHelper;
import com.taotao.delayjob.core.RetryTaskHub;
import com.taotao.delayjob.core.RetryTaskScheduler;
import com.taotao.delayjob.core.mapper.RetryInstMapper;
import com.taotao.delayjob.core.utils.ConcurrentUtil;
import lombok.Getter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 *
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2024/7/17 14:31
 */
@Getter
@Configuration
@MapperScan("com.taotao.delayjob.core.mapper")
public class RetryTaskConfig {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private RetryInstMapper retryInstMapper;
    @Value("${retry.thread-pool.core-pool-size:5}")
    private int corePoolSize;
    @Value("${retry.thread-pool.maximum-pool-size:10}")
    private int maximumPoolSize;
    @Value("${retry.thread-pool.keep-alive-seconds:300}")
    private int keepAliveSeconds;
    @Value("${retry.thread-pool.queue-capacity:300}")
    private int queueCapacity;


    @Value("${pagehelper.dialect:mysql}")
    private String helperDialect;

    @ConditionalOnMissingBean(PageInterceptor.class)
    @Bean
    public PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor0 = new PageInterceptor();
        Properties properties = new Properties();
        properties.put("helperDialect", helperDialect);
        //参数方法调用
        properties.put("supportMethodsArguments", "true");

        pageInterceptor0.setProperties(properties);
        return pageInterceptor0;
    }

    @Bean(initMethod = "start", destroyMethod = "destroy")
    public RetryTaskScheduler retryTaskScheduler(@Autowired RetryTaskHelper retryTaskHelper) {
        return new RetryTaskScheduler(dataSource, retryTaskHelper);
    }



    @Bean
    public RetryTaskHub retryTaskHub() {
        return new RetryTaskHub();
    }


    @Bean
    public RetryTaskHelper retryTaskHelper(@Autowired RetryTaskHub retryTaskHub, @Autowired ThreadPoolExecutor retryRrggerThreadPool) {
        return new RetryTaskHelper(retryInstMapper, retryTaskHub, retryRrggerThreadPool);
    }


    @ConditionalOnMissingBean(name = "retryRrggerThreadPool")
    @Bean("retryRrggerThreadPool")
    public ThreadPoolExecutor retryRrggerThreadPool() {
        return ConcurrentUtil.newThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveSeconds, queueCapacity, "retry-trigger-thread");

    }


}
